package socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Server1
{
    private ServerSocket serverSocket;
    private Socket socket;

    public Server1()
    {
        try
        {
            System.out.println("server is starting ......");
            serverSocket = new ServerSocket(8088);
            System.out.println("server is started .......");
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void start()
    {
        try
        {
            while (true)
            {
                System.out.println("waiting for client connect .......");
                socket = serverSocket.accept();
                System.out.println("there is a client connect successfully");
                Thread t1 = new Thread()
                {
                    @Override
                    public void run()
                    {
                        InputStream inputStream = null;
                        try
                        {
                            inputStream = socket.getInputStream();
                        } catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                        while (true)
                        {
                            int len = 0;
                            byte[] data = new byte[0];
                            try
                            {
                                len = inputStream.read();
                                data = new byte[len];
                                inputStream.read(data);
                            } catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                            if ("exit".equals(new String(data, 0, len, StandardCharsets.UTF_8)))
                                break;
                            System.out.println(new String(data, 0, len, StandardCharsets.UTF_8));
                        }
                    }
                };
            }
            } catch(Exception e)
            {
                e.printStackTrace();
            }
    }
}